<?php

class GradeController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout = '/layouts/triple_sidebar';
	public $_group_id = NULL;
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','create','update','admin','delete','test1','creategrade','deletecolumns','createtotal'),
				'roles'=>array('teacher'),
				'users'=>array('*'),
			),
			/*array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),*/
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$grade_model = Grade::model()->findAll();
		$model2 = new Grade;
		$students = $this->getGroup($id);
		$titles = array();
		if($students != null){
			$titles = $this->getColumnNames($students[0]->users_id);
			$this->fillStudentGrades($students, $titles);
		}
		$grades = $this->getGrades($students);
		if(isset($_POST['Grade'])){
				foreach($students as $st){
					foreach(Grade::model()->findAllByAttributes(array('userid'=>$st->users_id)) as $g0){
						if(isset($_POST['Grade'][$g0->id])){
							$model3 = new Grade;
							$model3->attributes = $_POST['Grade'][$g0->id];
							$temp = Grade::model()->findByPk($g0->id);
							$temp->grade = $model3->grade;
							$temp->update();
							//$this->refresh();
							//$this->redirect(array('view', 'id'=>1));
							}
						}
					}
				}
		
		$this->render('view',array(
			//'model'=>$this->loadModel($id),
			'model1'=>$this->loadGroupModel($id),
			'students'=>$students,
			'grades'=>$grades,
			'grade_model'=>$grade_model,
			'model2'=>$model2,
			'titles'=>$titles,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Grade;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Grade']))
		{
			$model->attributes=$_POST['Grade'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Grade']))
		{
			$model->attributes=$_POST['Grade'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Grade');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Grade('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Grade']))
			$model->attributes=$_GET['Grade'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Grade the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model1 = Group::model()->findByPk($id);
		$model=Grade::model()->findByPk($id);
		if($model1===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model1;
	}


	public function loadGroupModel($gid){
			$group = Group::model()->findByPk($gid);
			if($group === null){
					throw new CHttpException(404, 'The requested page does not exist.');
				}
			return $group;
		}
	/**
	 * Performs the AJAX validation.
	 * @param Grade $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='grade-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
		
	public function getGroup($gid){
			$group_students = UserProfiles::model()->findAllByAttributes(array('group_id'=>$gid));
			return $group_students;
		}
		
	public function getGrades($students_list){
			$grades = array(); 
			 $counter = 0; $row_counter = 0;
			foreach($students_list as $s){
				$temp = Grade::model()->findAllByAttributes(array('userid'=>$s->users_id));
				$grade_rows = array();
				$row_counter = 0;
				foreach($temp as $t){
						$grade_rows[$row_counter] = array();
						array_push($grade_rows[$row_counter], $t);
						$row_counter++;
					}
				$grades[$counter] = array();
				array_push($grades[$counter], $grade_rows);
				$counter++;
				}
				
			return $grades;
		}
	public function actionTest1($id = 5){
			$grade_model = Grade::model()->findAll();
			$model2 = new Grade;
			$students = $this->getGroup($id);
			$grades = $this->getGrades($students);
			if(isset($_POST['Grade'])){
				foreach($students as $st){
					foreach(Grade::model()->findAllByAttributes(array('userid'=>$st->users_id)) as $g0){
						if(isset($_POST['Grade'][$g0->id])){
							$model3 = new Grade;
							$model3->attributes = $_POST['Grade'][$g0->id];
							$temp = Grade::model()->findByPk($g0->id);
							$temp->grade = $model3->grade;
							$temp->update();
							//$this->refresh();
							//$this->redirect(array('view', 'id'=>1));
							}
						}
					}
				}
			//'model'=>$this->loadModel($id),
			//'model1'=>$this->loadGroupModel($id),
			//
			//'grades'=>$grades,
			//'grade_model'=>$grade_model,
			//
			
			$this->render('test1', array(
				'students'=>$students,
				'model2'=>$model2,
			));
		}
	
	public function getGroupId(){
			return $this->_group_id;
		}
	
	public function getColumnNames($sid){
			$grades1 = Grade::model()->findAllByAttributes(array('userid'=>$sid));
			$titles = array(); $counter = 0;
			foreach($grades1 as $g1){
				$titles[$counter] = $g1->title;
				$counter++;
				}
			$sorted_titles = array_unique($titles);
			return $sorted_titles;
		}
		
	public function actionCreateGrade(){
			$created_grade = new Grade;
			$created_grade->attributes = $_POST['Grade'];
			$id = $created_grade->grade;
			$student_lists = $this->getGroup($id);
			foreach($student_lists as $st){
					$new_grade1 = new Grade;
					$new_grade1->userid = $st->users_id;
					$new_grade1->grade = 0;
					$new_grade1->DateCreated = date_create()->format('Y-m-d H:i:s');
					$new_grade1->type = $created_grade->type;
					$new_grade1->title = $created_grade->title;
					$new_grade1->insert();
					$this->redirect(array('view', 'id'=>$id));
				}
		}
		
	public function fillStudentGrades($students_list, $titles_list){
			foreach($titles_list as $title){
				foreach($students_list as $students){
						if(Grade::model()->findByAttributes(array('title'=>$title, 'userid'=>$students->users_id)) == null){
									$tempGrade = new Grade;
									$tempGrade->userid = $students->users_id;
									$tempGrade->title = $title;
									$tempGrade->type = $this->getTypes($title);
									$tempGrade->grade = 0;
									$tempGrade->DateCreated = date_create()->format('Y-m-d H:i:s');
									$tempGrade->insert();
							}
					}						
			}
						
				
		}
		
	public function getTypes($title){
			return Grade::model()->findByAttributes(array('title'=>$title))->type;
		}
		
	public function actionDeleteColumns($title, $id){
			Grade::model()->deleteAllByAttributes(array('title'=>$title));
			$this->redirect(array('view', 'id'=>$id));
		}

	public function actionCreateTotal(){
			$total = new Totals;
			$titles = $this->getColumnNames(4);
			if(isset($_POST['Totals'])){
				$total->attributes = $_POST['Totals'];
				$str = $total->formula;
				$counter = 1; $s = "order";
				$eq_order = array();
				while(strpos($str,";") != 0){
						$pos0 = strpos($str,')');
						$str_half = substr($str, 0, $pos0+1);
						$pos1 = strrpos($str_half, '(');
						$pos2 = $pos0 - $pos1;
						$str_r = substr($str, $pos1, $pos0+1);
						$eq_order[$counter] = $str_r;
						$str = substr_replace($str, $s . $counter, $pos1, $pos0+1);
						$counter += 1;
					}
				$counter = 1;	
				foreach($eq_order as $eq){
						if($counter == sizeof($eq_order)){
								
							}
						else{
								foreach($titles as $title){
										$this->sortEquations($title, $eq);
									}
							}
						$counter += 1;
					}
					$this->redirect(array('events/index'));
				}
		}
		
	public function sortEquations($title, $eq){
			$variables = array(); 
			$operators = array();
			$counter = 1; $counter2 = 1;
			$token = strtok($eq,"()+-*/");
			while($token != false){
					$word = ltrim($token, " ");
					$word1 = rtrim($word, " ");
					if($word1 === $title){
							$variables[$counter] = $title;
							$counter++;
						}
					$token = strtok("()+-*/");
				}
				
			$op_array = str_split($eq);
			foreach($op_array as $op){
					if($op == "+"){
							$operators[$counter2] = "+";
							$counter2 += 1;
						}
					elseif($op == "-"){
							$operators[$counter2] = "-";
							$counter2 += 1;
						}
					elseif($op == "*"){
							$operators[$counter2] = "*";
							$counter2 += 1;
						}
					elseif($op == "/"){
							$operators[$counter2] = "/";
							$counter2 += 1;
						}
				}
		}
}

